﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

namespace CsvLib
{
    /// <summary>
    /// 
    /// </summary>
    public class Line : IEnumerable<Cell>
    {
        public int Index { get; }
        readonly string[] _data;
        readonly Title title;

        public Cell this[int index]
        {
            get
            {
                if (title == null)
                {
                    return new Cell(this, index, null, _data[index]);
                }
                else
                {
                    return new Cell(this, index, title.List[index], _data[index]);
                }
            }
        }

        public Cell this[string titleName]
        {
            get
            {
                if (titleName == null)
                {
                    throw new ApplicationException("No Title");
                }
                int colIndex = title.StringToInt[titleName];
                return new Cell(this, colIndex, titleName, _data[colIndex]);
            }
        }

        public Line(Title title, string[] data, int index)
        {
            this.title = title;
            _data = data;
            Index = index;
        }

        public struct Enumrator : IEnumerator<Cell>
        {
            int i;
            Line line;
            readonly IEnumerator dataEnumer;

            public Enumrator(Line line, IEnumerator dataEnumer) : this()
            {
                this.line = line;
                this.dataEnumer = dataEnumer;
                i = -1;
            }

            public Cell Current => line[i];

            object IEnumerator.Current => Current;

            public void Dispose()
            {
            }

            public bool MoveNext()
            {
                if (dataEnumer.MoveNext())
                {
                    i++;
                    return true;
                }
                else
                {
                    i = -1;
                    return false;
                }
            }

            public void Reset()
            {
                i = -1;
            }
        }

        public IEnumerator<Cell> GetEnumerator()
        {
            return new Enumrator(this, _data.GetEnumerator());
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
}
